package org.ilc;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.webapp.WebAppContext;

import java.io.File;

/**
 * @author malongbo
 */
public class Lanucher {
    private static Log log = LogFactory.getLog (Lanucher.class);
    private static Server server =null;

    public static void main(String[] args) {
        long startTime=System.currentTimeMillis();
        if(log.isInfoEnabled()){
            log.info("start ilc push server...");
        }

        //加载服务器根目录
        File file=new File("");
        File currDir=new File(file.getAbsolutePath());
        String rootDir;
//        rootDir = currDir.getParent();
        rootDir="D:\\work\\temp\\ilc-push\\";

        //启动服务器
        Bootstrap.start(rootDir);

        boolean httpEnable=Bootstrap.getContext().getConfig().getBoolean(Constants.HTTP_ENABLE_KEY);

        //如果启动http服务器
        if(httpEnable){
            //启动http服务器
            if(log.isInfoEnabled()){
                log.info("start ilc push http server...");
            }
            server = new Server(Bootstrap.getContext().getConfig().getInt(Constants.HTTP_PORT_KEY, 8999));
            try {
                WebAppContext context = new WebAppContext(rootDir+ File.separator+Constants.HTTP_WEBAPP_DIR_NAME,"/");
                context.setTempDirectory(new File(Bootstrap.getContext().getWorkDir()));
                server.setHandler(context);
                server.start();
                server.join();
            } catch (Exception e) {
                log.error (e);
            }
        }

        /**
         *  设置停止服务器的回调接口
         */
        Runtime rt = Runtime.getRuntime();
        rt.addShutdownHook(new Thread() {
            public void run() {
                Bootstrap.shutDown();
                try {
                    if(null!=server)
                        server.stop();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        if(log.isInfoEnabled()){
            log.info("ilc push  server started,use time:" + (System.currentTimeMillis()-startTime));
        }
    }
}
